/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Entity;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Istc
 */
public class AccountDB {

    Connection conn;

    public AccountDB() {
        conn = new DataOperations().getConnection();
    }

    public boolean checkAcc(int num) {
        try {
            PreparedStatement state = conn.prepareStatement("SELECT COUNT(CardNumber) FROM [SweetBank].[dbo].[Account] where CardNumber=?");
            state.setInt(1, num);
            ResultSet rs = state.executeQuery();
            rs.next();
            int tg = rs.getInt(1);
            if (tg > 0) {
                return true;
            } else {
                return false;
            }
        } catch (SQLException ex) {
            Logger.getLogger(AccountDB.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

    public Account getAcc(int num) {
        try {
            PreparedStatement state = conn.prepareStatement("SELECT * FROM [SweetBank].[dbo].[Account] where CardNumber=?");
            state.setInt(1, num);
            ResultSet rs = state.executeQuery();
            if (rs.next())
            {
                Account acc=new Account();
                acc.setCardNumber(rs.getInt("CardNumber"));
                acc.setCvv(rs.getInt("Cvv"));
                acc.setBalance(rs.getFloat("Balance"));
                return acc;
            }else return null;
        } catch (SQLException ex) {
            Logger.getLogger(AccountDB.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
    public boolean transfer(int num1, int cvv, int num2, float amount)
    {
        if (!checkAcc(num2)) return false;
        if (!checkAcc(num1)) return false;
        Account acc1=getAcc(num1);
        if (cvv!=acc1.getCvv()) return false;
        Account acc2=getAcc(num2);
        if (amount>acc1.getBalance()) return false;
        acc1.setBalance(acc1.getBalance()-amount);
        acc2.setBalance(acc2.getBalance()+amount);
        updateAcc(acc1);
        updateAcc(acc2);
        return true;
    }
    public void updateAcc(Account acc)
    {
         try {
            PreparedStatement state = conn.prepareStatement("UPDATE [SweetBank].[dbo].[Account] SET Balance=? where CardNumber=?");
            state.setInt(2, acc.getCardNumber());
            state.setFloat(1, acc.getBalance());
            state.executeUpdate();            
        } catch (SQLException ex) {
            Logger.getLogger(AccountDB.class.getName()).log(Level.SEVERE, null, ex);
            
        }
    }
}
